package com.bytech.admin.biz.controller.music;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bytech.admin.biz.annotation.NoAdminCheck;
import com.bytech.admin.biz.service.music.MusicService;
import com.bytech.common.biz.entity.base.BaseResult;
import com.bytech.common.biz.entity.music.Music;
import com.bytech.common.biz.entity.music.MusicDto;
import com.bytech.common.biz.entity.music.MusicQuery;
import com.bytech.common.biz.enums.CommonStatusEnum;
import com.bytech.common.config.UploadConfig;
import com.bytech.common.utils.DateUtils;
import com.bytech.common.utils.StringUtils;

/**
 * @Author Zhao
 * @Create 2021/12/23 16:18
 */
@Controller
@RequestMapping("/music")
public class MusicController {

    @Resource
    private MusicService musicService;
    @Resource
    private UploadConfig uploadConfig;

    @GetMapping("/list")
    public String toMusicList(Model model) {
        model.addAttribute("status", CommonStatusEnum.validValues());
        return "/music/list";
    }

    @PostMapping("/pageByQuery")
    @ResponseBody
    public BaseResult<Page<MusicDto>> pageMusicByQuery(MusicQuery<Music> musicQuery) {
        return BaseResult.<Page<MusicDto>>success().data(musicService.pageArticleByQuery(musicQuery)).build();
    }

    @GetMapping("/getAllUsable")
    @ResponseBody
    @NoAdminCheck
    public BaseResult<List<Music>> getAllUsable() {
        return BaseResult.<List<Music>>success()
                .data(musicService.list(new LambdaQueryWrapper<Music>().eq(Music::getStatus, CommonStatusEnum.NORMAL.getValue())))
                .build();
    }

    @PostMapping("/delete")
    @ResponseBody
    public BaseResult<?> doDeleteMusic(Long id) {
        musicService.removeById(id);
        return BaseResult.success("删除成功").build();
    }

    @GetMapping("/toUpload")
    public String toUploadMusic() {
        return "/music/upload";
    }

    @PostMapping("/uploadCover")
    @ResponseBody
    public BaseResult<String> doUploadCover(MultipartFile file, Model model) {
        String dateFolder = "/" + DateUtils.parseDate(new Date(), DateUtils.TightDateFormat);
        String imageFolder = uploadConfig.getFullImageFolder(dateFolder);
        File folder = new File(imageFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        OutputStream out = null;
        String fileUrl = null;
        try {
            String originalFileName = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFileName);
            if (StringUtils.isBlank(extension) || !UploadConfig.ACCEPT_IMAGE_EXTENSIONS.contains(extension)) {
                return BaseResult.<String>error("不支持的文件类型【" + extension + "】").build();
            }
            String newImgName = RandomStringUtils.randomAlphanumeric(10);
            String newFullFileName = String.format("%s/%s.%s", imageFolder, newImgName, extension);
            out = new FileOutputStream(newFullFileName);
            out.write(file.getBytes());
            out.flush();
            fileUrl = uploadConfig.getUploadLocation(newFullFileName);
        } catch (Exception e) {
            return BaseResult.<String>error("上传失败").build();
        }
        return BaseResult.<String>success("上传成功！").data(fileUrl).build();
    }

    @PostMapping("/uploadMusic")
    @ResponseBody
    public BaseResult<String> doUploadMusic(MultipartFile file, Model model) {
        String musicFolder = uploadConfig.getMusicFolder();
        File folder = new File(musicFolder);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        OutputStream out = null;
        String fileUrl = null;
        try {
            String originalFileName = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalFileName);
            if (StringUtils.isBlank(extension) || !UploadConfig.ACCEPT_MUSIC_EXTENSIONS.contains(extension)) {
                return BaseResult.<String>error("不支持的文件类型【" + extension + "】").build();
            }
            String newFullFileName = String.format("%s/%s", musicFolder, originalFileName);
            out = new FileOutputStream(newFullFileName);
            out.write(file.getBytes());
            out.flush();
            fileUrl = uploadConfig.getUploadLocation(newFullFileName);
        } catch (Exception e) {
            return BaseResult.<String>error("上传失败").build();
        }
        return BaseResult.<String>success("上传成功！").data(fileUrl).build();
    }

    @PostMapping("/saveMusic")
    @ResponseBody
    public BaseResult<?> doSaveMusic(Music music) {
        return musicService.add(music);
    }
}
